package com.yougou.ui.mine;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.yougou.R;
import com.yougou.base.BaseActivity;
import com.yougou.data.model.User;
import com.yougou.utils.ToastUtils;
import com.yougou.utils.UserManager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class UserInfoActivity extends BaseActivity {
    
    private Toolbar mToolbar;
    private LinearLayout mLayoutAvatar;
    private ImageView mIvAvatar;
    private LinearLayout mLayoutUsername;
    private TextView mTvUsername;
    private LinearLayout mLayoutPhone;
    private TextView mTvPhone;
    private LinearLayout mLayoutGender;
    private TextView mTvGender;
    private LinearLayout mLayoutBirthday;
    private TextView mTvBirthday;
    private LinearLayout mLayoutPassword;
    
    private User mUser;
    private String mSelectedGender = "";
    private String mSelectedBirthday = "";
    
    private ActivityResultLauncher<String> mImagePicker;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        
        // 初始化图片选择器
        mImagePicker = registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                uri -> {
                    if (uri != null) {
                        try {
                            // 将图片复制到应用私有目录
                            String savedPath = saveImageToPrivateStorage(uri);
                            
                            if (savedPath != null) {
                                android.util.Log.d("UserInfo", "头像保存路径: " + savedPath);
                                android.util.Log.d("UserInfo", "文件是否存在: " + new java.io.File(savedPath).exists());
                                
                                // 保存头像路径
                                mUser.setAvatar(savedPath);
                                
                                // 持久化到本地存储
                                com.yougou.utils.UserDataManager.updateUserProfile(
                                        mUser.getUid(), null, null, savedPath);
                                
                                // 更新当前用户
                                UserManager.updateUser(mUser);
                                
                                // 显示头像（跳过缓存，确保显示最新图片）
                                java.io.File avatarFile = new java.io.File(savedPath);
                                
                                // 直接使用Bitmap设置图片（绕过Glide可能的问题）
                                try {
                                    android.graphics.Bitmap bitmap = android.graphics.BitmapFactory.decodeFile(savedPath);
                                    if (bitmap != null) {
                                        android.util.Log.d("UserInfo", "Bitmap解码成功: " + bitmap.getWidth() + "x" + bitmap.getHeight());
                                        
                                        // 直接使用Glide的bitmap方法
                                        Glide.with(UserInfoActivity.this)
                                                .asBitmap()
                                                .load(avatarFile)
                                                .skipMemoryCache(true)
                                                .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.NONE)
                                                .circleCrop()
                                                .listener(new com.bumptech.glide.request.RequestListener<android.graphics.Bitmap>() {
                                                    @Override
                                                    public boolean onLoadFailed(com.bumptech.glide.load.engine.GlideException e, Object model, 
                                                            com.bumptech.glide.request.target.Target<android.graphics.Bitmap> target, boolean isFirstResource) {
                                                        android.util.Log.e("UserInfo", "Glide加载失败: " + e.getMessage());
                                                        e.printStackTrace();
                                                        return false;
                                                    }
                                                    
                                                    @Override
                                                    public boolean onResourceReady(android.graphics.Bitmap resource, Object model, 
                                                            com.bumptech.glide.request.target.Target<android.graphics.Bitmap> target, 
                                                            com.bumptech.glide.load.DataSource dataSource, boolean isFirstResource) {
                                                        android.util.Log.d("UserInfo", "Glide加载成功！Bitmap: " + resource.getWidth() + "x" + resource.getHeight());
                                                        return false;
                                                    }
                                                })
                                                .into(mIvAvatar);
                                        
                                        android.util.Log.d("UserInfo", "已调用Glide.into()");
                                    } else {
                                        android.util.Log.e("UserInfo", "Bitmap解码失败");
                                        mIvAvatar.setImageResource(R.drawable.ic_mine);
                                    }
                                } catch (Exception ex) {
                                    android.util.Log.e("UserInfo", "加载图片异常", ex);
                                    mIvAvatar.setImageResource(R.drawable.ic_mine);
                                }
                                
                                ToastUtils.show(this, "头像更新成功");
                            } else {
                                ToastUtils.show(this, "头像保存失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.show(this, "头像上传失败：" + e.getMessage());
                        }
                    }
                }
        );
        
        initView();
        initData();
    }
    
    @Override
    protected void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(v -> finish());
        
        mLayoutAvatar = findViewById(R.id.layout_avatar);
        mIvAvatar = findViewById(R.id.iv_avatar);
        mLayoutUsername = findViewById(R.id.layout_username);
        mTvUsername = findViewById(R.id.tv_username);
        mLayoutPhone = findViewById(R.id.layout_phone);
        mTvPhone = findViewById(R.id.tv_phone);
        mLayoutGender = findViewById(R.id.layout_gender);
        mTvGender = findViewById(R.id.tv_gender);
        mLayoutBirthday = findViewById(R.id.layout_birthday);
        mTvBirthday = findViewById(R.id.tv_birthday);
        mLayoutPassword = findViewById(R.id.layout_password);
        
        // 点击事件
        mLayoutAvatar.setOnClickListener(v -> changeAvatar());
        mLayoutUsername.setOnClickListener(v -> changeUsername());
        mLayoutPhone.setOnClickListener(v -> changePhone());
        mLayoutGender.setOnClickListener(v -> changeGender());
        mLayoutBirthday.setOnClickListener(v -> changeBirthday());
        mLayoutPassword.setOnClickListener(v -> changePassword());
    }
    
    @Override
    protected void initData() {
        mUser = UserManager.getCurrentUser();
        if (mUser == null) {
            ToastUtils.show(this, "请先登录");
            finish();
            return;
        }
        
        updateUI();
    }
    
    
    private void updateUI() {
        // 显示头像
        String avatar = mUser.getAvatar();
        android.util.Log.d("UserInfo", "updateUI - 头像路径: " + avatar);
        if (avatar != null && !avatar.isEmpty()) {
            // 判断是文件路径还是URI
            if (avatar.startsWith("content://")) {
                Glide.with(this)
                        .load(Uri.parse(avatar))
                        .skipMemoryCache(true)
                        .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.NONE)
                        .placeholder(R.drawable.ic_mine)
                        .error(R.drawable.ic_mine)
                        .circleCrop()
                        .into(mIvAvatar);
            } else {
                // 文件路径
                Glide.with(this)
                        .load(new java.io.File(avatar))
                        .skipMemoryCache(true)
                        .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.NONE)
                        .placeholder(R.drawable.ic_mine)
                        .error(R.drawable.ic_mine)
                        .circleCrop()
                        .into(mIvAvatar);
            }
        } else {
            mIvAvatar.setImageResource(R.drawable.ic_mine);
        }
        
        // 显示用户名
        if (mUser.getUsername() != null && !mUser.getUsername().isEmpty()) {
            mTvUsername.setText(mUser.getUsername());
        } else {
            mTvUsername.setText("未设置");
        }
        
        // 显示手机号
        if (mUser.getPhone() != null && !mUser.getPhone().isEmpty()) {
            mTvPhone.setText(maskPhone(mUser.getPhone()));
        } else {
            mTvPhone.setText("未设置");
        }
        
        // 显示性别
        String gender = mUser.getGender();
        if (gender != null && !gender.isEmpty()) {
            mTvGender.setText(gender);
            mSelectedGender = gender;
        } else {
            mTvGender.setText("未设置");
        }
        
        // 显示生日
        String birthday = mUser.getBirthday();
        if (birthday != null && !birthday.isEmpty()) {
            mTvBirthday.setText(birthday);
            mSelectedBirthday = birthday;
        } else {
            mTvBirthday.setText("未设置");
        }
    }
    
    
    private void changeAvatar() {
        // 启动图片选择器
        mImagePicker.launch("image/*");
    }
    
    
    private void changeUsername() {
        // 创建输入对话框
        android.widget.EditText editText = new android.widget.EditText(this);
        editText.setText(mUser.getUsername());
        editText.setSelection(editText.getText().length());
        editText.setHint("请输入用户名");
        editText.setPadding(50, 30, 50, 30);
        
        new AlertDialog.Builder(this)
                .setTitle("修改用户名")
                .setView(editText)
                .setPositiveButton("确定", (dialog, which) -> {
                    String newUsername = editText.getText().toString().trim();
                    if (newUsername.isEmpty()) {
                        ToastUtils.show(this, "用户名不能为空");
                        return;
                    }
                    if (newUsername.length() < 3 || newUsername.length() > 20) {
                        ToastUtils.show(this, "用户名长度应为3-20个字符");
                        return;
                    }
                    
                    // 检查用户名是否已被使用
                    if (com.yougou.utils.UserDataManager.isUsernameTaken(newUsername, mUser.getUid())) {
                        ToastUtils.show(this, "该用户名已被使用");
                        return;
                    }
                    
                    // 更新本地存储的用户信息
                    com.yougou.utils.UserDataManager.updateUserInfo(mUser.getUid(), newUsername, mUser.getPhone());
                    
                    // 保存到当前用户
                    mUser.setUsername(newUsername);
                    UserManager.updateUser(mUser);
                    updateUI();
                    ToastUtils.show(this, "修改成功");
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    
    private void changePhone() {
        // 创建输入对话框
        android.widget.EditText editText = new android.widget.EditText(this);
        editText.setText(mUser.getPhone());
        editText.setSelection(editText.getText().length());
        editText.setHint("请输入手机号");
        editText.setInputType(android.text.InputType.TYPE_CLASS_PHONE);
        editText.setPadding(50, 30, 50, 30);
        
        new AlertDialog.Builder(this)
                .setTitle("修改手机号")
                .setView(editText)
                .setPositiveButton("确定", (dialog, which) -> {
                    String newPhone = editText.getText().toString().trim();
                    if (newPhone.isEmpty()) {
                        ToastUtils.show(this, "手机号不能为空");
                        return;
                    }
                    if (!newPhone.matches("^1[3-9]\\d{9}$")) {
                        ToastUtils.show(this, "请输入有效的手机号");
                        return;
                    }
                    
                    // 检查手机号是否已被使用
                    if (com.yougou.utils.UserDataManager.isPhoneTaken(newPhone, mUser.getUid())) {
                        ToastUtils.show(this, "该手机号已被使用");
                        return;
                    }
                    
                    // 更新本地存储的用户信息
                    com.yougou.utils.UserDataManager.updateUserInfo(mUser.getUid(), mUser.getUsername(), newPhone);
                    
                    // 保存到当前用户
                    mUser.setPhone(newPhone);
                    UserManager.updateUser(mUser);
                    updateUI();
                    ToastUtils.show(this, "修改成功");
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    
    private void changePassword() {
        // 创建自定义布局
        android.widget.LinearLayout layout = new android.widget.LinearLayout(this);
        layout.setOrientation(android.widget.LinearLayout.VERTICAL);
        layout.setPadding(50, 30, 50, 30);
        
        // 旧密码输入框
        android.widget.EditText etOldPassword = new android.widget.EditText(this);
        etOldPassword.setHint("请输入旧密码");
        etOldPassword.setInputType(android.text.InputType.TYPE_CLASS_TEXT | 
                                   android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        layout.addView(etOldPassword);
        
        // 新密码输入框
        android.widget.EditText etNewPassword = new android.widget.EditText(this);
        etNewPassword.setHint("请输入新密码");
        etNewPassword.setInputType(android.text.InputType.TYPE_CLASS_TEXT | 
                                   android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        android.widget.LinearLayout.LayoutParams params1 = new android.widget.LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params1.topMargin = 20;
        etNewPassword.setLayoutParams(params1);
        layout.addView(etNewPassword);
        
        // 确认密码输入框
        android.widget.EditText etConfirmPassword = new android.widget.EditText(this);
        etConfirmPassword.setHint("请确认新密码");
        etConfirmPassword.setInputType(android.text.InputType.TYPE_CLASS_TEXT | 
                                       android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        android.widget.LinearLayout.LayoutParams params2 = new android.widget.LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params2.topMargin = 20;
        etConfirmPassword.setLayoutParams(params2);
        layout.addView(etConfirmPassword);
        
        new AlertDialog.Builder(this)
                .setTitle("修改密码")
                .setView(layout)
                .setPositiveButton("确定", (dialog, which) -> {
                    String oldPassword = etOldPassword.getText().toString().trim();
                    String newPassword = etNewPassword.getText().toString().trim();
                    String confirmPassword = etConfirmPassword.getText().toString().trim();
                    
                    if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
                        ToastUtils.show(this, "所有字段都不能为空");
                        return;
                    }
                    
                    if (newPassword.length() < 6) {
                        ToastUtils.show(this, "新密码长度不能少于6位");
                        return;
                    }
                    
                    if (!newPassword.equals(confirmPassword)) {
                        ToastUtils.show(this, "两次输入的密码不一致");
                        return;
                    }
                    
                    // 修改密码
                    boolean success = com.yougou.utils.UserDataManager.changePassword(
                            mUser.getUid(), oldPassword, newPassword);
                    
                    if (success) {
                        ToastUtils.show(this, "密码修改成功");
                    } else {
                        ToastUtils.show(this, "旧密码错误");
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    
    private void changeGender() {
        String[] genders = {"男", "女", "保密"};
        int checkedItem = -1;
        
        // 查找当前选中的性别
        for (int i = 0; i < genders.length; i++) {
            if (genders[i].equals(mSelectedGender)) {
                checkedItem = i;
                break;
            }
        }
        
        new AlertDialog.Builder(this)
                .setTitle("选择性别")
                .setSingleChoiceItems(genders, checkedItem, (dialog, which) -> {
                    mSelectedGender = genders[which];
                })
                .setPositiveButton("确定", (dialog, which) -> {
                    if (mSelectedGender != null && !mSelectedGender.isEmpty()) {
                        // 保存性别到本地存储
                        com.yougou.utils.UserDataManager.updateUserProfile(
                                mUser.getUid(), mSelectedGender, null, null);
                        
                        // 保存到当前用户
                        mUser.setGender(mSelectedGender);
                        UserManager.updateUser(mUser);
                        updateUI();
                        ToastUtils.show(this, "修改成功");
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    
    private void changeBirthday() {
        Calendar calendar = Calendar.getInstance();
        
        // 如果已经设置了生日，解析日期
        if (mSelectedBirthday != null && !mSelectedBirthday.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                calendar.setTime(sdf.parse(mSelectedBirthday));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        DatePickerDialog dialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    // 格式化日期
                    mSelectedBirthday = String.format(Locale.CHINA, "%d-%02d-%02d", year, month + 1, dayOfMonth);
                    
                    // 保存生日到本地存储
                    com.yougou.utils.UserDataManager.updateUserProfile(
                            mUser.getUid(), null, mSelectedBirthday, null);
                    
                    // 保存到当前用户
                    mUser.setBirthday(mSelectedBirthday);
                    UserManager.updateUser(mUser);
                    updateUI();
                    ToastUtils.show(this, "修改成功");
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        
        dialog.show();
    }
    
    
    private String maskPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    private String saveImageToPrivateStorage(Uri uri) {
        try {
            android.util.Log.d("UserInfo", "开始保存图片，URI: " + uri);
            
            // 创建应用私有目录
            java.io.File avatarDir = new java.io.File(getFilesDir(), "avatars");
            if (!avatarDir.exists()) {
                boolean created = avatarDir.mkdirs();
                android.util.Log.d("UserInfo", "创建目录: " + avatarDir.getAbsolutePath() + ", 成功: " + created);
            }
            
            // 生成文件名
            String fileName = "avatar_" + mUser.getUid() + "_" + System.currentTimeMillis() + ".jpg";
            java.io.File destFile = new java.io.File(avatarDir, fileName);
            android.util.Log.d("UserInfo", "目标文件: " + destFile.getAbsolutePath());
            
            // 复制图片
            java.io.InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                android.util.Log.e("UserInfo", "无法打开输入流");
                return null;
            }
            
            java.io.FileOutputStream outputStream = new java.io.FileOutputStream(destFile);
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            int totalBytes = 0;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                totalBytes += bytesRead;
            }
            
            inputStream.close();
            outputStream.close();
            
            android.util.Log.d("UserInfo", "图片复制完成，大小: " + totalBytes + " bytes");
            
            // 删除旧头像
            String oldAvatar = mUser.getAvatar();
            if (oldAvatar != null && !oldAvatar.isEmpty() && !oldAvatar.startsWith("content://")) {
                java.io.File oldFile = new java.io.File(oldAvatar);
                if (oldFile.exists()) {
                    boolean deleted = oldFile.delete();
                    android.util.Log.d("UserInfo", "删除旧头像: " + deleted);
                }
            }
            
            return destFile.getAbsolutePath();
        } catch (Exception e) {
            android.util.Log.e("UserInfo", "保存图片失败", e);
            e.printStackTrace();
            return null;
        }
    }
}

